package com.shijie.component;

import com.alibaba.fastjson.JSON;
import com.shijie.component.redis.RedisClient;
import com.shijie.component.redis.RedisKey;
import com.shijie.core.ResultCode;
import com.shijie.core.ResultGenerator;
import com.shijie.core.annotation.NoLogin;
import com.shijie.core.annotation.RequiresPermissions;
import com.shijie.utils.CommonUtil;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Component
@Aspect
public class AspectComponent {

    private static final Logger logger = LoggerFactory.getLogger(AspectComponent.class);
    @Autowired
    private ErpUserService erpUserService;
    @Autowired
    private AppUserService appUserService;

    @Autowired
    private RedisClient redisClient;

    @Pointcut("execution(public * com.shijie.controller.app.*.*(..))")
    public void app() {

    }

    @Around("app()")
    public Object aroundApp(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = CommonUtil.getRequest();
        logger.info("请求接口：{}，请求IP：{}，请求参数：{}",
                request.getRequestURI(), CommonUtil.getClientIp(), JSON.toJSONString(request.getParameterMap()));
        NoLogin annotation = CommonUtil.getAnnotation(joinPoint, NoLogin.class);
        if (null == annotation && !appUserService.isLogin()) {
            return ResultGenerator.error(ResultCode.UNAUTHORIZED, "未登录");
        }
        return joinPoint.proceed();
    }


    @Pointcut("execution(public * com.shijie.controller.erp.*.*(..))")
    public void erp() {

    }

    @SuppressWarnings("unchecked")
    @Around("erp()")
    public Object aroundErp(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = CommonUtil.getRequest();
        logger.info("请求接口：{}，请求IP：{}，请求参数：{}",
                request.getRequestURI(), CommonUtil.getClientIp(), JSON.toJSONString(request.getParameterMap()));
        NoLogin annotation = CommonUtil.getAnnotation(joinPoint, NoLogin.class);
        if (null == annotation && !erpUserService.isLogin()) {
            return ResultGenerator.error(ResultCode.UNAUTHORIZED, "未登录");
        }
        RequiresPermissions requiresPermissions = CommonUtil.getAnnotation(joinPoint, RequiresPermissions.class);
        if (requiresPermissions != null) {
            //校验权限
            //Set<String> permissions = (Set<String>) cacheManager.getCache(Caches.ERP_PERMISSION_CACHE.name()).get(erpUserService.getUserId()).get();
            Set<String> permissions = redisClient.get(String.format(RedisKey.ERP_PERMISSION_CACHE, erpUserService.getUserId()));

            if (permissions == null || !this.match(Arrays.asList(requiresPermissions.value()), permissions)) {
                return ResultGenerator.error(ResultCode.UNAUTHORIZED, "用户未操作权限");
            }
        }
        return joinPoint.proceed();
    }
    
    private boolean match(List<String> requestPermisssions ,Set<String> permissionAll){
    	for(String s : requestPermisssions){
    		Iterator<String> set =  permissionAll.iterator();
        	while(set.hasNext()){
        		if(set.next().equals(s)){
        			return true;
        		}
        	}
    	}
    	return false;
    }
}
